<template>
    <div class="content">
        <div id="c"></div>
        <!-- 加载完成后，如果想隐藏进度条可以设置  v-if="loadedData!==100"，也就是loadedData等于100隐藏进度条-->
        <div v-if="isshow" style="position: absolute;width:400px;" :style="{ left: left + 'px', top: top + 'px' }">
            <el-progress :text-inside="true" :stroke-width="30" :percentage="loadedData"></el-progress>
        </div>
        <!-- 模型列表 -->
        <div class="legend" id="legend" style="left: 1000;">
            <div class="row title">模型</div>
            <div class="row">

            </div>
        </div>
    </div>
</template>

<script>
import * as THREE from "three"
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader"
let mouse = {}

export default {
    name: "module",
    data() {
        return {
            renderer: null,
            scene: null,
            camera: null,
            controls: null,
            mouse: null,
            // loadedData关联加载进度条
            // total: 479766720,
            total: 322869504,
            loadedData: 0,
            left: (window.innerWidth - 400) / 2,
            top: (window.innerHeight - 30) / 2,
            isshow: 1
        }
    },
    mounted() {
        // 监听窗口尺寸变化
        window.addEventListener(
            "resize",
            () => {
                this.camera.aspect = window.innerWidth / window.innerHeight
                this.camera.updateProjectionMatrix()
                this.renderer.setSize(window.innerWidth, window.innerHeight)
            },
            false
        )
        // 监听鼠标
        window.addEventListener("pointerdown", this.selectObject)
        this.init()
        this.render()
        this.animate()
    },
    beforeDestroy() {
        this.renderer = null
        this.scene = null
        this.camera = null
        this.controls = null
        this.mouse = null
    },
    methods: {
        init() {
            // 渲染器
            const canvas = document.querySelector('#c')
            // const container = document.createElement('div')
            // document.body.appendChild(container)

            this.renderer = new THREE.WebGLRenderer({ antialias: true })
            this.renderer.setPixelRatio(window.devicePixelRatio)
            this.renderer.setSize(canvas.clientWidth, canvas.clientHeight)
            this.renderer.toneMapping = THREE.ACESFilmicToneMapping
            this.renderer.toneMappingExposure = 1
            this.renderer.outputEncoding = THREE.sRGBEncoding

            canvas.appendChild(this.renderer.domElement)
            // 相机
            this.camera = new THREE.PerspectiveCamera(45, canvas.clientWidth / canvas.clientHeight, 0.1, 2000)
            this.camera.position.set(184.95493837084203, 145.05411333221153, 190.13306686972422)
            // 场景
            this.scene = new THREE.Scene()

            // 轨道控制
            this.controls = new OrbitControls(this.camera, this.renderer.domElement)
            // this.controls.addEventListener( 'change', render ); // use if there is no animation loop
            this.controls.minDistance = 5
            this.controls.maxDistance = 1000
            this.controls.target.set(0, 0, -0.4)
            this.controls.update()

            // 坐标线
            // const axes = new THREE.AxesHelper(500)
            // this.scene.add(axes)

            // Grid 地面网格线
            // const grid = new THREE.GridHelper(300, 300, 0x888888, 0x444444);
            // this.scene.add(grid);

            this.load3D()
        },
        load3D() {
            new RGBELoader().load('textures/equirectangular/royal_esplanade_1k.hdr', (texture) => {
                texture.mapping = THREE.EquirectangularReflectionMapping
                this.scene.background = texture
                this.scene.environment = texture
                this.render()

                const loader = new GLTFLoader()
                const dracoLoader = new DRACOLoader()
                dracoLoader.setDecoderPath('/draco/')
                dracoLoader.preload()
                loader.setDRACOLoader(dracoLoader)

                loader.load('module/gcy.glb', (gltf) => {
                    this.scene.add(gltf.scene)
                    this.render()
                    console.log('渲染完成')
                    this.isshow = false
                    this.showChildren()
                }, (xhr) => {
                    this.loadedData = Math.floor(xhr.loaded / this.total * 100)
                })
            })
        },
        render() {
            this.renderer.render(this.scene, this.camera)
        },
        animate() {
            requestAnimationFrame(this.animate)
            this.render()
        },
        selectObject(event) {
            if (this.isshow) return
            if (event.button != 0) return
            // 二维向量
            mouse = new THREE.Vector2()
            // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1
            mouse.y = - (event.clientY / window.innerHeight) * 2 + 1

            // 光线投射
            const raycaster = new THREE.Raycaster()
            raycaster.setFromCamera(mouse, this.camera)

            console.log(this.scene);
            const intersected = raycaster.intersectObjects(this.scene.children, true)
            console.log(intersected)
            if (intersected.length) {
                const found = intersected[0]
                const faceIndex = found.faceIndex
                const geometry = found.object.geometry
                const material = found.object.material
                // const id = ifcLoader.ifcManager.getExpressId(geometry, faceIndex);

                // const modelID = found.object.modelID;
                // ifcLoader.ifcManager.createSubset({ modelID, ids: [id], scene, removePrevious: true, material: highlightMaterial });
                // const props = ifcLoader.ifcManager.getItemProperties(modelID, id, true);
                // console.log(props);
                // renderer.render(scene, camera);
                material.color.set(0x00FF00)
                //console.log(intersects[0].object.material.color);

            }

        },


        showChildren() {
            console.log(this.scene)
            let allObject = this.scene.children[0].children[1];
            console.log(allObject)
            console.log(this.scene.children)

            for (let oneObj in allObject.children) {
                console.log(oneObj)
            }

            console.log('showChildren')

            var MyDiv = document.getElementById("legend");
            var button = document.createElement("input");
            button.setAttribute("type", "button");
            button.setAttribute("value", this.scene.children);
            button.setAttribute("id", "id");

            button.style.width = "12%";
            button.setAttribute("onclick", "showObject(this.id)");
            MyDiv.appendChild(button);
        }
    }
}
</script>

<style scoped lang="less">
.content {
    width: 100%;
    height: 100vh;
    overflow: hidden;

    #c {
        width: 100%;
        height: 100%;
    }

    .legend {
        position: absolute;

        right: 0;
        top: 0;
        width: 200px;
        height: 140px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
    }

    .legend>.row {
        width: 100%;
        height: 24px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
    }

    .legend>.row.title {
        color: #fff;
        font-size: 16px;
        line-height: 20px;
        margin-bottom: 8px;
        text-align: center;
        justify-content: center;
    }

    .legend>.row>.color {
        width: 80px;
        height: 4px;
        margin: 0 8px;
    }

    .legend>.row>label {
        color: #fff;
        margin: 0 8px;
    }

}
</style>
